package com.huawei.service;

import org.springframework.stereotype.Component;

import javax.jws.Oneway;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;


@Component
@ServerEndpoint(value = "/websocket/{sid}")
public class WebSocketServer {

    private static int onlineCount = 0;
    private static CopyOnWriteArrayList<WebSocketServer> webSocketServers = new CopyOnWriteArrayList<>();
    private Session session;
    private String sid = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) throws IOException {
        this.session = session;
        webSocketServers.add(this);
        addOnlineCount();
        this.sid=sid;
        try {
            sendMessage("连接成功");
        } catch (EOFException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose() {
        webSocketServers.remove(this);
        subOnLineCount();
    }

    @OnMessage
    public void onMessage(String message,Session session){
        for (WebSocketServer item : webSocketServers) {
            try {
                item.sendMessage(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    @OnError
    public void onError(Session session,Throwable error){
        error.printStackTrace();
    }
    public void sendMessage(String message) throws  IOException{
        this.session.getBasicRemote().sendText(message);
    }
    public static void sendInfo(String message,@PathParam("sid") String sid) throws  IOException{
        for (WebSocketServer item : webSocketServers) {
            try {
                if(sid==null){
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            }catch (IOException e){
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        WebSocketServer.onlineCount++;
    }
    public static synchronized void subOnLineCount(){
        WebSocketServer.onlineCount--;
    }

}

